package io.lkt.modules.sys.controller;

import io.lkt.common.redis.RedisCacheUtil;
import io.lkt.common.utils.PageUtils;
import io.lkt.common.utils.R;
import io.lkt.common.validator.ValidatorUtils;
import io.lkt.modules.job.utils.HttpGetPostUtils;
import io.lkt.modules.sys.entity.*;
import io.lkt.modules.sys.service.*;
import io.lkt.modules.sys.utils.SysConstant;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 品牌信息表
 *
 * @author xss
 * @email dustwas@163.com
 * @date 2019-03-11 17:13:26
 */
@RestController
@RequestMapping("/sys/bbrandinfo")
public class BBrandInfoController extends AbstractController {
    @Autowired
    private BBrandInfoService bBrandInfoService;

    @Autowired
    private BArticleTypeInfoService bArticleTypeInfoService;

    @Autowired
    private BBrandSupplyInfoService bBrandSupplyInfoService;

    @Autowired
    private BArticleInfoService bArticleInfoService;

    @Autowired
    BUserBrandInfoService bUserBrandInfoService;

    @Autowired
    BUserBrandInfoService bUserBrandInfoDao;

    @Value("${serviceUrls}")
    private String serviceUrls;

    @Autowired
    RedisCacheUtil redisCacheUtil;

//    public final static String ArticleBrandAndTypeInfoMapper="http://47.107.152.128:8080/cache/delCache?key=com.tulele.vtool.mapper.ArticleBrandAndTypeInfoMapper";

//    public final static String BrandInfoMapper="http://47.107.152.128:8080/cache/delCache?key=com.tulele.vtool.mapper.BrandInfoMapper";

//    public final static String UserBrandInfoMapper="http://47.107.152.128:8080/cache/delCache?key=com.tulele.vtool.mapper.UserBrandInfoMapper";

    public final static String ArticleBrandAndTypeInfoMapper="https://service.rrdsp.cn/cache/delCache?key=com.tulele.vtool.mapper.ArticleBrandAndTypeInfoMapper";

    public final static String BrandInfoMapper="https://service.rrdsp.cn/cache/delCache?key=com.tulele.vtool.mapper.BrandInfoMapper";

    public final static String UserBrandInfoMapper="https://service.rrdsp.cn/cache/delCache?key=com.tulele.vtool.mapper.UserBrandInfoMapper";



    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:bbrandinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = bBrandInfoService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 品牌
     * @param id
     * @return
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("sys:bbrandinfo:list")
    public R queryAll(Integer id){
        List<BBrandNameEntity> brandInfo=bBrandInfoService.queryAll(id);
        //List<String> name=new ArrayList<>();
//        for(BBrandInfoEntity bb:brandInfo){
//            name.add(bb.getBrandName());
//            if(bb.getBrandName().length()>20){
//                bb.setBrandName(bb.getBrandName().substring(0,16));
//            }
//        }
        return R.ok().put("brandInfo", brandInfo);
                //.put("name",name);
    }

    @RequestMapping("/queryByName")
    // @RequiresPermissions("sys:bbrandinfo:list")
    public R queryByName(@RequestBody BBrandInfoEntity bBrandInfo){
        String brandName=bBrandInfo.getBrandName();
        System.out.println(brandName);
        BBrandInfoEntity brandInfo=bBrandInfoService.queryByName(brandName);
        return R.ok().put("brandInfo", brandInfo);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:bbrandinfo:info")
    public R info(@PathVariable("id") Integer id){
        BBrandInfoEntity bBrandInfo = bBrandInfoService.getById(id);

        // 补位文章品牌 id
        if(bBrandInfo != null && bBrandInfo.getLinkBrand() !=null){
            BBrandInfoEntity linkBrandNameInfo = this.bBrandInfoService.getById(bBrandInfo.getLinkBrand());
            if(linkBrandNameInfo != null && linkBrandNameInfo.getLinkBrandName() !=null) {
                bBrandInfo.setLinkBrandName(linkBrandNameInfo.getLinkBrandName());
            }
        }

        // 补位文章分类 id
        if(bBrandInfo != null && bBrandInfo.getLinkType() !=null) {
            BArticleTypeInfoEntity linkTypeNameInfo = this.bArticleTypeInfoService.getById(bBrandInfo.getLinkType());
            if (linkTypeNameInfo != null && linkTypeNameInfo.getArticleTypeName() != null) {
                bBrandInfo.setLinkTypeName(linkTypeNameInfo.getArticleTypeName());
            }
        }
        return R.ok().put("bBrandInfo", bBrandInfo);
    }

    public List<BBrandNameEntity> infoById(Integer id){
        List<BBrandNameEntity> brandInfo=bBrandInfoService.queryAll(id);
        return brandInfo;
    }

    /**
     * 保存
     */
    @Transactional
    @RequestMapping("/save")
    @RequiresPermissions("sys:bbrandinfo:save")
    public R save(@RequestBody BBrandInfoEntity bBrandInfo)throws Exception{
        String brandName=bBrandInfo.getBrandName();
        if(bBrandInfoService.queryByName(brandName)!=null ){
            return R.error("品牌已存在");
        }
        System.out.println(bBrandInfo.getBrandAlias()+"---");
        String alias=bBrandInfo.getBrandAlias();
        String keyWord=bBrandInfo.getBrandKeyWord();

        // 补位文章品牌 id
        bBrandInfo.setLinkBrand(0);
        BBrandInfoEntity linkBrandNameInfo = this.bBrandInfoService.queryByName(bBrandInfo.getLinkBrandName());
        if(linkBrandNameInfo != null && linkBrandNameInfo.getId() !=null){
            bBrandInfo.setLinkBrand(linkBrandNameInfo.getId());
        }

        // 补位文章分类 id
//        BArticleTypeInfoEntity linkTypeNameInfo = this.bArticleTypeInfoService.queryByName(bBrandInfo.getLinkTypeName());
//        if(linkTypeNameInfo != null && linkTypeNameInfo.getId() !=null){
//            bBrandInfo.setLinkType(linkTypeNameInfo.getId());
//        }

        // 组装保存绑定品牌名称
        String brandBindingNames = bBrandInfo.getBrandBindingNames();
        String brandBindingIds = "";
        if (brandBindingNames != null && !brandBindingNames.trim().equals("")) {
            String[] brandBindings = brandBindingNames.split(",");

            for (String brandNameInfo : brandBindings) {
                BBrandInfoEntity bBrandInfoEntity = bBrandInfoService.queryByName(brandNameInfo);
                if(bBrandInfoEntity != null) {
                    brandBindingIds = brandBindingIds + "," + bBrandInfoEntity.getId();
                }
            }
            brandBindingIds = brandBindingIds.substring(1);
        }
        bBrandInfo.setBrandBindingIds(brandBindingIds);

        if(alias!=null || alias!="") {
            bBrandInfo.setBrandAlias(bBrandInfo.getBrandAlias().replaceAll(",", "，"));
        }
        if(keyWord!=null || keyWord!="") {
            bBrandInfo.setBrandKeyWord(bBrandInfo.getBrandKeyWord().replaceAll("，",","));
        }
        String articleTypeIds=bBrandInfo.getArticleTypeIds();
        Integer articleTypeId=bBrandInfo.getArticleTypeId();
        System.out.println(articleTypeIds);
        bBrandInfo.setBrandOpenStatus(1);

        //获取当前登录用户
        SysUserEntity curUser = getUser();
        bBrandInfo.setCreateBy(curUser.getUsername());

        bBrandInfo.setCreateTime(new Date());
        boolean result=bBrandInfoService.save(bBrandInfo);
        HttpClient httpClient = HttpClientBuilder.create().build();
        if(result){
            if (articleTypeIds !="0" && !articleTypeIds.equals("0")) {
                Map<String, Object> map = new HashMap<>();
                map.put("articleBrandId", bBrandInfo.getId());
                map.put("articleTypeIds", articleTypeIds);
                map.put("createTime", new Date());
                bBrandInfoService.addBrandAndType(map);
            }
            if(articleTypeId!=999) {
                BBrandSupplyInfoEntity bBrandSupplyInfoEntity = new BBrandSupplyInfoEntity();
                bBrandSupplyInfoEntity.setBrandId(bBrandInfo.getId());
                bBrandSupplyInfoEntity.setArticleTypeId(bBrandInfo.getArticleTypeId());
                bBrandSupplyInfoEntity.setSupplyStatus(1);
                bBrandSupplyInfoEntity.setCreateTime(new Date());
                bBrandSupplyInfoService.save(bBrandSupplyInfoEntity);
            }
        }
//        HttpGet get = new HttpGet(ArticleBrandAndTypeInfoMapper);
//        httpClient.execute(get);
//        get = new HttpGet(BrandInfoMapper);
//        httpClient.execute(get);

        HttpGetPostUtils.delCache(serviceUrls, "ArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "BrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "UserBrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }

    /**
     * 修改
     */
    @Transactional
    @RequestMapping("/update")
    @RequiresPermissions("sys:bbrandinfo:update")
    public R update(@RequestBody BBrandInfoEntity bBrandInfo)throws Exception{
        ValidatorUtils.validateEntity(bBrandInfo);
        HttpClient httpClient = HttpClientBuilder.create().build();

        // 补位文章品牌 id
        bBrandInfo.setLinkBrand(0);
        BBrandInfoEntity linkBrandNameInfo = this.bBrandInfoService.queryByName(bBrandInfo.getLinkBrandName());
        if(linkBrandNameInfo != null && linkBrandNameInfo.getId() != null){
            bBrandInfo.setLinkBrand(linkBrandNameInfo.getId());
        }

        // 补位文章分类 id
//        BArticleTypeInfoEntity linkTypeNameInfo = this.bArticleTypeInfoService.queryByName(bBrandInfo.getLinkTypeName());
//        if(linkTypeNameInfo != null && linkTypeNameInfo.getId() != null){
//            bBrandInfo.setLinkType(linkTypeNameInfo.getId());
//        }

        // 组装保存绑定品牌名称
        String brandBindingNames = bBrandInfo.getBrandBindingNames();
        String brandBindingIds = "";
        if (brandBindingNames != null && !brandBindingNames.trim().equals("")) {
            String[] brandBindings = brandBindingNames.split(",");

            for (String brandNameInfo : brandBindings) {
                BBrandInfoEntity bBrandInfoEntity = bBrandInfoService.queryByName(brandNameInfo);
                if(bBrandInfoEntity != null) {
                    brandBindingIds = brandBindingIds + "," + bBrandInfoEntity.getId();
                }
            }
            brandBindingIds = brandBindingIds.substring(1);
        }
        bBrandInfo.setBrandBindingIds(brandBindingIds);

        //别名、关键字格式化
        if(bBrandInfo.getBrandAlias()!=null&&bBrandInfo.getBrandKeyWord()!=null) {
            bBrandInfo.setBrandAlias(bBrandInfo.getBrandAlias().replaceAll(",", "，"));
            bBrandInfo.setBrandKeyWord(bBrandInfo.getBrandKeyWord().replaceAll("，", ","));
        }
        //修改品牌信息
        boolean result=bBrandInfoService.updateById(bBrandInfo);
        //获取品牌信息
        List<BBrandInfoEntity> brandList=bBrandInfoService.typeByBrandId(bBrandInfo.getId());
        // 删除品牌 top50 缓存 start
        String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + bBrandInfo.getId();
        redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
        // 删除品牌 top50 缓存 end
        brandList.removeAll(Collections.singleton(null));
        System.out.println(brandList.size()+">>>>>>>>>>>>>>");
        Integer ArticleTypeId=bBrandInfo.getArticleTypeId();
        String ArticleTypeIds=bBrandInfo.getArticleTypeIds();
//        if(ArticleTypeId==999){
//            ArticleTypeId=null;
//        }
//        if(ArticleTypeIds=="0" || ArticleTypeIds.equals("0")){
//            ArticleTypeIds=null;
//        }
        //新增内部分类
        BBrandSupplyInfoEntity bBrandSupplyInfoEntity=new BBrandSupplyInfoEntity();
        bBrandSupplyInfoEntity.setBrandId(bBrandInfo.getId());
        bBrandSupplyInfoEntity.setArticleTypeId(ArticleTypeId);
        bBrandSupplyInfoEntity.setSupplyStatus(1);
        //如果品牌修改成功
        if(result){
            Map<String, Object> map = new HashMap<>();
            //品牌ID、文章分类
            map.put("articleBrandId", bBrandInfo.getId());
            map.put("articleTypeIds", ArticleTypeIds);
            //存在修改时未选择  处理为删除
            if (brandList.size()>0 && ArticleTypeIds!=null && ArticleTypeIds.equals("0")) {
                bBrandInfoService.delBrandAndType(bBrandInfo.getId());
            }else if (brandList == null && (ArticleTypeIds==null || (ArticleTypeIds!=null && !ArticleTypeIds.equals("0")))) {
                //不存在 新增
                map.put("createTime", new Date());
                bBrandInfoService.addBrandAndType(map);
            }else if(brandList.size()!=0 &&  (ArticleTypeIds==null || (ArticleTypeIds!=null && !ArticleTypeIds.equals("0")))){
                map.put("modifyTime", new Date());
                bBrandInfoService.upType(map);
            }
        }
        if(bBrandInfo.getArticleTypeId()!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("brandId", bBrandInfo.getId());
            List<BBrandSupplyInfoEntity> supply=bBrandSupplyInfoService.queryList(map);
            if(supply.size()>0 && ArticleTypeId.equals(999)){
                bBrandInfoService.delsupply(bBrandInfo.getId());
            }else if(supply.size()!=0 && ArticleTypeId!=999){
                bBrandSupplyInfoEntity.setModifyTime(new Date());
                bBrandSupplyInfoService.upType(bBrandSupplyInfoEntity);
            }else if(supply.size()==0 && ArticleTypeId!=999){
                bBrandSupplyInfoEntity.setCreateTime(new Date());
                bBrandSupplyInfoService.save(bBrandSupplyInfoEntity);
            }
        }
        //去除缓存
//        HttpGet get = new HttpGet(ArticleBrandAndTypeInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls,"ArticleBrandAndTypeInfoMapper");
//        get = new HttpGet(BrandInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls, "UserRelateArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "BrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "UserBrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }
    /**
     * 新增并修改
     */
    @Transactional
    @RequestMapping("/updates")
    @RequiresPermissions("sys:bbrandinfo:update")
    public R updates(@RequestBody BBrandInfoEntity bBrandInfo)throws Exception{
        ValidatorUtils.validateEntity(bBrandInfo);
        HttpClient httpClient = HttpClientBuilder.create().build();
        String brandName=bBrandInfo.getBrandName();
        if(bBrandInfoService.queryByName(brandName)!=null ){
            return R.error("品牌已存在");
        }
        BBrandInfoEntity brandInfo=new BBrandInfoEntity();
        // 组装保存绑定品牌名称
        String brandBindingNames = bBrandInfo.getBrandBindingNames();
        String brandBindingIds = "";
        if (brandBindingNames != null && !brandBindingNames.trim().equals("")) {
            String[] brandBindings = brandBindingNames.split(",");

            for (String brandNameInfo : brandBindings) {
                BBrandInfoEntity bBrandInfoEntity = bBrandInfoService.queryByName(brandNameInfo);
                if(bBrandInfoEntity != null) {
                    brandBindingIds = brandBindingIds + "," + bBrandInfoEntity.getId();
                }
            }
            brandBindingIds = brandBindingIds.substring(1);
        }
        brandInfo.setBrandBindingIds(brandBindingIds);

        brandInfo.setId(bBrandInfo.getId());
        // 删除品牌 top50 缓存 start
        String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + bBrandInfo.getId();
        redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
        // 删除品牌 top50 缓存 end
        brandInfo.setHandleStatus(1);
        String articleTypeIds=bBrandInfo.getArticleTypeIds();
        bBrandInfo.setCreateTime(new Date());
        bBrandInfo.setOriginalBrandId(bBrandInfo.getId());
        bBrandInfo.setBrandOpenStatus(1);
        bBrandInfo.setBrandSource(1);
        boolean result=bBrandInfoService.save(bBrandInfo);
        System.out.println(result);
        if(result){
            if(!articleTypeIds.equals("0")) {
                Map<String, Object> map = new HashMap<>();
                map.put("articleBrandId", bBrandInfo.getId());
                map.put("articleTypeIds", articleTypeIds);
                map.put("createTime", new Date());
                int num = bBrandInfoService.addBrandAndType(map);
                System.out.println(num);
            }
            System.out.println(brandInfo);
            bBrandInfoService.updateById(brandInfo);
        }
//        HttpGet get = new HttpGet(ArticleBrandAndTypeInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls,"ArticleBrandAndTypeInfoMapper");
//        get = new HttpGet(BrandInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls, "UserRelateArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "BrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "UserBrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }
    /**
     * 删除
     */
    @Transactional
    @RequestMapping("/delete")
    @RequiresPermissions("sys:bbrandinfo:update")
    public R delete(@RequestBody Integer id)throws Exception{
        HttpClient httpClient = HttpClientBuilder.create().build();
        Map<String,Object> map=new HashMap<>();
        map.put("brandId",id);
        List<BArticleInfoEntity> brandList = bArticleInfoService.queryList(map);
        for(BArticleInfoEntity artice:brandList){
            bArticleInfoService.removeById(artice.getId());
            System.out.println("删除文章："+artice.getId());
        }
        int num=bUserBrandInfoDao.delUserBrand(id);
        bBrandInfoService.removeById(id);
        System.out.println("删除品牌："+id);
        // 删除品牌 top50 缓存 start
        String articleBrandIdKey = SysConstant.PLANT_FORM_BRAND_ARTICLE_TOP50 + id;
        redisCacheUtil.removeSingleCacheMaster(articleBrandIdKey);
        // 删除品牌 top50 缓存 end
//        HttpGet get = new HttpGet(BrandInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls,"BrandInfoMapper");
//        get = new HttpGet(UserBrandInfoMapper);
//        httpClient.execute(get);
        HttpGetPostUtils.delCache(serviceUrls, "UserRelateArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleTypeInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "BrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "UserBrandInfoMapper");
        HttpGetPostUtils.delCache(serviceUrls, "ArticleInfoMapper");
        return R.ok();
    }

}
